<template>
  <div class="posts">
    <!-- Post Item -->
    <div class="card card-body mb-3">
      <div class="row">
        <div class="col-md-2">
          <a>
            <img
              class="rounded-circle d-nonse d-md-block ml-4"
              style="width:100px"
              :src="post.avatar"
            >
          </a>
          <br>
          <p class="text-center">{{post.name}}</p>
        </div>
        <div class="col-md-10">
          <p class="lead">{{post.text}}</p>
          <span v-if="showAction">
            <button type="button" class="btn btn-light mr-1" @click="like(post._id)">
              <i class="fas fa-thumbs-up"></i>
              <span class="badge badge-light">{{post.likes.length}}</span>
            </button>
            <button type="button" class="btn btn-light mr-1" @click="unlike(post._id)">
              <i class="text-secondary fas fa-thumbs-down"></i>
            </button>
            <router-link :to="'/post/'+post._id" class="btn btn-info mr-1">鼓励留言</router-link>

            <!-- 判断是否可以删除留言 -->
            <button
              v-if="user != null && user.id == post.user"
              type="button"
              class="btn btn-danger mr-1"
              @click="deletePost(post._id)"
            >
              <i class="fas fa-times"/>
            </button>
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  data() {
    return {};
  },
  computed: {
    user() {
      return this.$store.getters.user;
    }
  },
  methods: {
    deletePost(id) {
      this.$axios
        .delete(`http://localhost:5000/api/posts/${id}`)
        .then(res => {
          //删除成功  更新数据
          this.$emit("update");
        })
        .catch(err => {
          console.log(err.response.data);
        });
    },
    like(id) {
      this.$axios
        .post(`http://localhost:5000/api/posts/like/${id}`)
        .then(res => {
          this.$emit("update");
        })
        .catch(err => {
          // console.log(err.response.data);
          alert(err.response.data.alreadyliked);
        });
    },
    unlike(id) {
      this.$axios
        .post(`http://localhost:5000/api/posts/unlike/${id}`)
        .then(res => {
          this.$emit("update");
        })
        .catch(err => {
          // console.log(err.response.data);
          alert(err.response.data.notliked);
        });
    }
  },
  props: {
    post: Object,
    showAction: Boolean
  },
  components: {}
};
</script>

<style scoped lang="stylus">
</style>
